<template>
  <div
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    "
    v-if="loading"
  >
    <a-spin :spinning="loading"> </a-spin>
  </div>
  <a-table
    v-else
    :dataSource="dataSource"
    :columns="columns"
    :pagination="query"
    @change="onChange"
    force-render
    :row-selection="rowSelectionActive ? rowSelection : null"
    rowKey="id"
  >
    <template #bodyCell="{ column = {}, text, record, index }">
      <template v-if="column.key === 'action'">
        <!-- <edit-button
              :data="record"
              :tableId="tableInfo.id"
              v-model:editing="record.editing"
              v-model:loading="record.loading"
              v-model:isAdding="isAdding"
              @submit="onSubmit(record)"
            />
            <a-button
              v-if="record.editing"
              type="link"
              style="padding: 4px 6px"
              @click="onCancel(record)"
            >
              取消
            </a-button>
            <delete-button
              :data="record"
              v-else="record.editing"
              @operated="update"
            /> -->
      </template>
      <template v-else>
        <template
          v-if="
            Object.prototype.toString.call(record[column.key]) ===
            '[object Array]'
          "
        >
          <a-dropdown arrow>
            <iconfont
              name="#icon-gengduo"
              style="
                color: #1677ff;
                font-size: 18px;
                margin-left: 5px;
                outline: 0;
                cursor: pointer;
              "
            />
            <template #overlay>
              <a-menu style="max-height: 300px; overflow-y: auto">
                <a-menu-item v-for="value in record[column.key]">
                  {{ value }}
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else>
          <a-input
            type="text"
            v-model:value="record[column.key]"
            :disabled="record.loading"
            v-if="record.editing"
            placeholder="请输入"
            :maxlength="100"
          />
          <template v-else>
            {{ text }}
          </template>
        </template>
      </template>
    </template>
  </a-table>
</template>
<script setup>
import { ref, watch, toRaw, onMounted } from 'vue'
import { message as Message } from 'ant-design-vue'
import ATable from '@/components/table.vue'
import EditButton from './table-structure-edit.vue'
import DeleteButton from './table-structure-delete.vue'
import AddButton from './table-structure-add.vue'
import iconfont from '@/components/iconfont.vue'

import { getStructTable } from '@/api/db.js'
import { useRowSelection, useRowSelectionActive } from './provide-context.js'

/**
 * 入参
 */
let props = defineProps({
  tableInfo: { type: Object, default: () => ({}) },
  categoryName: { type: String, default: () => '' },
})

/**
 * table查询逻辑
 */
let query = ref({})
let columns = ref([])
let dataSource = ref([])
let loading = ref(false)
async function update() {
  loading.value = true
  try {
    let { current, pageSize } = query.value
    let result = await getStructTable({
      ...query.value,
      pageNum: current,
    })

    query.value.current = result?.data?.pageNum || current
    query.value.pageSize = result?.data?.pageSize || pageSize
    query.value.total = result?.data?.total || 0

    let tableHeaderMap = JSON.parse(props.tableInfo.tableHeader)
    columns.value = Object.keys(tableHeaderMap).map(key => {
      let title = tableHeaderMap[key]
      let dataIndex = `row${key}`
      return {
        title,
        dataIndex,
        key: dataIndex,
        width: title.length * 20 + 50, // 根据标题长度计算宽度
      }
    })

    // columns.value.push({
    //   title: '操作',
    //   key: 'action',
    //   width: 150,
    // })
    console.log(columns)
    let records = result.data?.records || []
    dataSource.value = records.map((item, index) => {
      let data = JSON.parse(item.data || {})
      let rowData = {
        tableInfoId: item.tableInfoId,
        id: item.id,
        editing: false,
        loading: false,
      }
      for (let key in data) {
        let value = data[key]
        rowData[`row${key}`] = value
      }
      return rowData
    })
    console.log(dataSource)
  } catch (e) {
    Message.error(`结构化数据查询失败![${e.message}]`)
  }
  loading.value = false
}

//table组件翻页事件，调用hooks
function onChange({ current, pageSize }, filters, sorter) {
  query.value.current = current
  query.value.pageSize = pageSize
  // query.value.filters = filters
  // sortCreatetimeType.value = sorter
  //添加过滤状态
  // columns?.value.forEach(column => {
  //   let { key } = column
  //   column.filteredValue = filters?.[key]
  // })

  update()
}
//初始化调用
// onMounted(() => {
//   query.value.current = 1
//   query.value.pageSize = 10
//   update()
// })
//tableInfo变化
watch(
  () => props.tableInfo,
  tableInfo => {
    query.value.current = 1
    query.value.pageSize = 10
    query.value.tableInfoId = tableInfo.id
    update()
  },
  { immediate: true },
)

/**
 * 编辑与删除
 */
function onSubmit(record) {
  if (record.id === undefined) {
    query.value.current = 1
  }
  update()
}
/**
 * 取消
 */
let isAdding = ref(false)
function onCancel(record) {
  if (record.id === undefined) {
    dataSource.value = dataSource.value.filter(item => item.id !== undefined)
    isAdding.value = false
  } else {
    record.editing = false
  }
}
/**
 * 多选
 */

let rowSelection = useRowSelection()
rowSelection.getCheckboxProps = record => ({
  disabled: record.dataType === 'folder' || record.dataStatus === 2,
})
let rowSelectionActive = useRowSelectionActive()
rowSelectionActive.value = true

onMounted(() => {
  window.getSelectedFileId = function () {
    return JSON.stringify(
      (rowSelection?.selectedRowInfos?.value || []).map(toRaw),
    )
  }
  window.clearSelectedFileId = function () {
    rowSelection.selectedRowKeys.value = []
  }
})
</script>
